﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;

namespace log
{
    class Http
    {
        public Http() { }


        public static void sendFile(string[] files,string uploadUrl, NameValueCollection data)
        {
            //NameValueCollection data = new NameValueCollection();
            //data.Add("name", "木子屋");
            //data.Add("url", "http://www.mzwu.com/");
            Http.HttpUploadFile(uploadUrl, files, data);


        }

        private static readonly Encoding DEFAULTENCODE = Encoding.UTF8;

        /// <summary>
        /// HttpUploadFile
        /// </summary>
        /// <param name="url"></param>
        /// <param name="file"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string uploadFile(string url, string file, NameValueCollection data)
        {
            return HttpUploadFile(url, file, data, DEFAULTENCODE);
        }

        /// <summary>
        /// HttpUploadFile
        /// </summary>
        /// <param name="url"></param>
        /// <param name="file"></param>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string HttpUploadFile(string url, string file, NameValueCollection data, Encoding encoding)
        {
            return HttpUploadFile(url, new string[] { file }, data, encoding);
        }

        /// <summary>
        /// HttpUploadFile
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string HttpUploadFile(string url, string[] files, NameValueCollection data)
        {
            return HttpUploadFile(url, files, data, DEFAULTENCODE);
        }

        /// <summary>
        /// HttpUploadFile
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files"></param>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string HttpUploadFile(string url, string[] files, NameValueCollection data, Encoding encoding)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            //1.HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;

            using (Stream stream = request.GetRequestStream())
            {
                //1.1 key/value
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                if (data != null)
                {
                    foreach (string key in data.Keys)
                    {
                        stream.Write(boundarybytes, 0, boundarybytes.Length);
                        string formitem = string.Format(formdataTemplate, key, data[key]);
                        byte[] formitembytes = encoding.GetBytes(formitem);
                        stream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }

                //1.2 file
                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                for (int i = 0; i < files.Length; i++)
                {
                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
                    byte[] headerbytes = encoding.GetBytes(header);
                    stream.Write(headerbytes, 0, headerbytes.Length);
                    using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
                    {
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            stream.Write(buffer, 0, bytesRead);
                        }
                    }
                }

                //1.3 form end
                stream.Write(endbytes, 0, endbytes.Length);
            }
            //2.WebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                return stream.ReadToEnd();
            }
        }

        public static JObject sendData(string url, string params_str,bool log=false)
        {
            
            string data = "&" + params_str;
            JObject jo = postJSON(url, data,log);
            if (jo.HasValues)
            {
                string status = jo.GetValue("status").ToString();//.Values.ToString();// HttpGet(url, signature, "");
                string msg = jo.GetValue("msg").ToString();
                if (status.Equals("200"))
                {
                    jo["info"] = msg;
                    jo["status"] = status;
                    jo["data"] = jo.GetValue("data") != null ? jo.GetValue("data").ToString() : null;
                    return jo;
                }
                else
                {
                    JObject jo1 = new JObject();
                    jo1["info"] = msg;
                    jo1["status"] = status;
                    jo1["error"] = jo.GetValue("error") != null ? jo.GetValue("error").ToString() : null;
                    return jo1;
                }

            }
            jo = new JObject();
            jo["info"] = "连接失败";
            jo["status"] = 0;
            return jo;

        }

        public static JObject post(string url, string postDataStr, bool log = false)//传入网址
        {
            JObject jo = new JObject();
            string resultstring = "";
            Encoding encoding = Encoding.UTF8;

            HttpWebRequest request = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);//这里的url指要获取的数据网址
                request.KeepAlive = false;
                request.Timeout = 15*1000;
            }
            catch (Exception ee1)
            {

                
                Log.info("sync postJSON error: url:" + url + ",result:" + resultstring + " message:" + ee1.Message + " trace:" + ee1.StackTrace);
                return jo;
            }

            request.Method = "Post";
            //request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/x-www-form-urlencoded";
            //request.ContentType = "application/json";
            request.Headers["lang"] = "zh-CN";
            // //Utils.Data.Log.info("request:post url:" + url + ",parameter:" + postDataStr+":header;lang="+App.lang);
            //Log.info("sync Post url:" + url + ",parameter:" + postDataStr);

            byte[] byte1 = encoding.GetBytes(postDataStr);
            request.ContentLength = byte1.Length;

            try
            {
                Stream newStream = request.GetRequestStream();
                newStream.Write(byte1, 0, byte1.Length);


                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
                resultstring = reader.ReadToEnd();



            }
            catch (Exception ee)
            {
                ////Utils.Data.Log.info("error: url:" + url + ",result:" + resultstring+" message:"+ee.Message+" trace:"+ee.StackTrace);
                Log.info("sync postJSON error: url:" + url + ",result:" + resultstring + " message:" + ee.Message + " trace:" + ee.StackTrace);
                return jo;
            }
            // //Utils.Data.Log.info("url:"+url+",result:"+resultstring);
            // MessageBox.Show(resultstring);
            try
            {
                if (log)
                {
                    Log.info("success: url:" + url + ",result:" + resultstring);
                }
                jo = (JObject)JsonConvert.DeserializeObject(resultstring);
            }
            catch (Exception ee)
            {
                ////Utils.Data.Log.info("error: url:" + url + ",result:" + resultstring + " message:" + ee.Message + " trace:" + ee.StackTrace);
                Log.info("sync postJSON error: url:" + url + ",result:" + resultstring + " message:" + ee.Message + " trace:" + ee.StackTrace);
            }

            return jo;

        }

        public static JObject getJSON(string url)//传入网址
        {
            JObject jo = new JObject();
            string resultstring = "";
            Encoding encoding = Encoding.UTF8;

            HttpWebRequest request = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);//这里的url指要获取的数据网址
                request.KeepAlive = false;
                request.Timeout = 300000;
            }
            catch (Exception ee1)
            {
                ////Utils.Data.Log.info("error: url:" + url + ",result:" + resultstring + " message:" + ee1.Message + " trace:" + ee1.StackTrace);
                Log.info("getJSON error: url:" + url + ",result:" + resultstring + " message:" + ee1.Message + " trace:" + ee1.StackTrace);
                return jo;
            }
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            request.Headers["lang"] = "zh-CN";
            // //Utils.Data.Log.info("request:get url:" + url + ",parameter:" +  ":header;lang=" + App.lang);
            //Log.info("GET url:" + url);


            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    resultstring = reader.ReadToEnd();
                }
            }
            catch (Exception ee)
            {
                //  MessageBox.Show("远程服务器连接失败");
                ////Utils.Data.Log.info("error: url:" + url + ",result:" + resultstring + " message:" + ee.Message + " trace:" + ee.StackTrace);
                Log.info("getJSON error: url:" + url + ",result:" + resultstring + " message:" + ee.Message + " trace:" + ee.StackTrace);
                return jo;
            }
            // MessageBox.Show(resultstring);
            try
            {
                //Log.info("success: url:" + url + ",result:" + resultstring);
                jo = (JObject)JsonConvert.DeserializeObject(resultstring);
            }
            catch
            {

            }

            return jo;

        }

    }
}
